package com.wolfking.web.ssoauth.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.wolfking.back.core.annotation.ssoauth.Sign;
import com.wolfking.back.core.bean.Area;
import com.wolfking.back.core.bean.Dict;
import com.wolfking.back.core.bean.User;
import com.wolfking.back.core.config.SsoConfig;
import com.wolfking.back.core.feignclient.AreaFeignClient;
import com.wolfking.back.core.feignclient.DictFeignClient;
import com.wolfking.back.core.util.DataEntityUtil;

/**
 * 区域的controller
 * <P>
 * 
 * @author wolfking@赵伟伟
 * @mail zww199009@163.com
 * @创作日期 2017年5月3日下午5:12:06
 * @版权 归wolfking所有
 */
@Controller
@RequestMapping("/area")
public class AreaController {

	@Autowired
	private AreaFeignClient areaFeignClient;

	@Autowired
	private DictFeignClient dictFeignClient;

	@Autowired
	private SsoConfig ssoConfig;

	@Sign(code="sys:area:list")
	@RequestMapping(value = "/list", method = { RequestMethod.GET, RequestMethod.POST })
	public String list(Model model) {
		List<Area> sourcelist = areaFeignClient.getAllArea().getBody();
		List<Area> list = Lists.newArrayList();
		sortList(list, sourcelist, "0", true);
		model.addAttribute("list", list);
		return "area/list";
	}

	/**
	 * 区域的编辑页面
	 * 
	 * @param model
	 * @param dict
	 * @return
	 */
	@Sign(code="sys:area:edit")
	@RequestMapping(value = "/edit", method = RequestMethod.GET)
	public String edit(Model model, Area area) {
		Area parent = new Area();
		if (StringUtils.isNotBlank(area.getId()))
			area = areaFeignClient.getArea(area.getId()).getBody();
		model.addAttribute("area", area);
		List<Area> list = areaFeignClient.getAllArea().getBody();
		model.addAttribute("list", list);
		List<Dict> types = dictFeignClient.getByType("sys_area_type").getBody();
		model.addAttribute("types", types);
		if (!"0".equals(area.getParentId())&&StringUtils.isNotEmpty(area.getParentId()))
			parent = areaFeignClient.getArea(area.getParentId()).getBody();
		model.addAttribute("parent",parent);
		return "area/edit";
	}

	/**
	 * 区域的保存或者修改
	 * 
	 * @param model
	 * @param dict
	 * @return
	 */
	@Sign(code="sys:area:edit")
	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	public String edits(Area area, User user, RedirectAttributes redirectAttributes) {
		DataEntityUtil.assemblyDataEntity(area, user);
		if (StringUtils.isNotBlank(area.getId())) {
			areaFeignClient.updateArea(area);
			redirectAttributes.addFlashAttribute("message", "修改区域成功");
		} else {
			areaFeignClient.addArea(area);
			redirectAttributes.addFlashAttribute("message", "添加区域成功");
		}
		return "redirect:" + ssoConfig.getSelfRootUrl() + "/area/list";
	}

	/**
	 * 删除区域
	 * 
	 * @param id
	 * @return
	 */
	@Sign(code="sys:area:edit")
	@RequestMapping(value = "/delete", method = RequestMethod.GET)
	public String delete(@RequestParam String id) {
		if (StringUtils.isNotBlank(id))
			areaFeignClient.deleteArea(id);
		return "redirect:" + ssoConfig.getSelfRootUrl() + "/area/list";
	}

	/**
	 * area的树数据
	 * 
	 * @param extId
	 * @param response
	 * @return
	 */
	@Sign
	@ResponseBody
	@RequestMapping(value = "/treeData")
	public List<Map<String, Object>> treeData(@RequestParam(required = false) String extId,
			HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<Area> list = areaFeignClient.getAllArea().getBody();
		for (int i = 0; i < list.size(); i++) {
			Area e = list.get(i);
			if (!e.getId().equals(extId)) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("pId", e.getParentId());
				map.put("name", e.getName());
				mapList.add(map);
			}
		}
		return mapList;
	}

	private void sortList(List<Area> list, List<Area> sourcelist, String parentId, boolean cascade) {
		for (int i = 0; i < sourcelist.size(); i++) {
			Area e = sourcelist.get(i);
			if (parentId.equals(e.getParentId())) {
				list.add(e);
				if (cascade) {
					// 判断是否还有子节点, 有则继续获取子节点
					for (int j = 0; j < sourcelist.size(); j++) {
						Area child = sourcelist.get(j);
						if (e.getId().equals(child.getParentId())) {
							sortList(list, sourcelist, e.getId(), true);
							break;
						}
					}
				}
			}
		}
	}

}
